export default class websocketUtil {
  url: string;
  data: any;
  isConnect: boolean;
  isCutoff: boolean;
  timeout: number;
  againTime: number;
  socketTask: any;
  heartbeatInterval: any;
  reconnectTimeOut: any;

  constructor(url: string, time: number) {
    this.isConnect = false; // 是否连接
    this.isCutoff = false; // 是否人为中断连接
    this.url = url; //地址
    this.data = null;
    //心跳检测
    this.timeout = time; //多少秒执行检测
    this.againTime = 3; //间隔多少秒进行重连
    this.heartbeatInterval = null; //检测服务器端是否还活着
    this.reconnectTimeOut = null; //重连之后多久再次重连

    this.connectSocketInit();
  }

  // 初始化连接
  connectSocketInit() {
    this.socketTask = uni.connectSocket({
      url: this.url,
      header: {
        'content-type': 'application/json',
      },
      success: () => {
        console.log('建立websocket连接');
        // 返回实例
        // return this.socketTask;
      },
    });

    this.socketTask.onOpen((res: any) => {
      console.log('WebSocket连接正常！');
      clearTimeout(this.reconnectTimeOut);
      clearInterval(this.heartbeatInterval);
      this.isConnect = true;
      this.isCutoff = false;
      this.heartbeatCheck();
    });

    // 这里仅是事件监听【如果socket关闭了会执行】
    this.socketTask.onClose(() => {
      console.log('WebSocket关闭了');
      this.isConnect = false;
      this.reconnect();
    });
  }

  //发送消息
  sendMsg(value: string) {
    // 注：只有连接正常打开中 ，才能正常成功发送消息
    this.socketTask.send({
      data: value,
      async success() {
        console.log('消息发送成功');
      },
    });
  }

  // 监听服务器信息
  getMsg(callback: (data: any) => void) {
    this.socketTask.onMessage((res: any) => {
      console.log(res);

      return callback(res.data);
    });
  }

  //开启心跳检测
  heartbeatCheck() {
    this.heartbeatInterval = setInterval(() => {
      this.data = { state: 1, method: 'heartbeat' };
      this.sendMsg(JSON.stringify(this.data));
    }, this.timeout * 1000);
  }

  //重新连接
  reconnect() {
    console.log('尝试重连');

    //停止发送心跳
    clearInterval(this.heartbeatInterval);
    //如果不是人为关闭的话，进行重连
    if (!this.isCutoff && !this.isConnect) {
      this.reconnectTimeOut = setTimeout(() => {
        this.connectSocketInit();
      }, this.againTime * 1000);
    }
  }

  // 关闭
  close() {
    this.isCutoff = true;
    this.socketTask.close({
      fail(err: any) {
        console.error('人为关闭websocket失败:' + err);
      },
    });
  }
}
